package com.seeyon.apps.cxgd.service.tc;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cxgd.entity.ResountEntity;
import com.seeyon.apps.cxgd.kit.FormCap4Kit;
import com.seeyon.apps.cxgd.kit.LogKit;
import com.seeyon.apps.cxgd.kit.StrKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.SQLException;
import java.util.*;

/**
 * 回推火车的service
 */
public class HCOrderService {
    private static Log log = LogFactory.getLog(HCOrderService.class);
    private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager)AppContext.getBean("cap4FormDataManager");

    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");

    private final static String HC_NUMBER = "TCHDDXX_001";

    /**
     * 回写火车表单数据
     * @param notifyData     推送主体
     * @param subNotifyType  推送子类型
     * @return
     */
    public ResountEntity hcOrder(String notifyData, String subNotifyType) {
        log.info("推送火车订单数据："+notifyData);
        //订单编号
        String orderNo = "";
        //oa申请单号
        String travelApplyNo = "";
        try{
            JSONObject jsonObject = JSON.parseObject(notifyData);
            Map<String,Object> travelDataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("travelData")),Map.class);
            orderNo = StrKit.str(jsonObject.get("orderNo"));
            travelApplyNo = StrKit.str(travelDataMap.get("TravelApplyNo"));
        }catch (Exception e){
            log.info("解析同城回退订单-火车数据异常！",e);
        }
        LogKit.addLog("同程回退订单-火车【订单号："+orderNo+"；OA申请单号："+travelApplyNo+"】", "同程回退订单-火车【订单号："+orderNo+"；OA申请单号："+travelApplyNo+"】", notifyData, "subNotifyType状态："+subNotifyType);
        //获取人员数据
        if(subNotifyType.equals("1")){
            //占座
            return addHcOrderOccupyingData(notifyData);
        }else if(subNotifyType.equals("2")){
            //出票
            return drawABill(notifyData);
        }else if(subNotifyType.equals("3")){
            //退票
            return refundTicket(notifyData);
        }else if(subNotifyType.equals("13")){
            //取消订单
            return cancelOrder(notifyData);
        }else{
            return new ResountEntity(true,"100","回写火车订单成功");
        }
    }


    /**
     * 占座
     * @param notifyData
     * @return
     */
    private ResountEntity addHcOrderOccupyingData(String notifyData){
        JSONObject jsonObject = JSON.parseObject(notifyData);
        //订单编号
        String orderNo = StrKit.str(jsonObject.get("orderNo"));
        //出发站
        String fromStation = StrKit.str(jsonObject.get("fromStation"));
        //到达站
        String toStation = StrKit.str(jsonObject.get("toStation"));
        //出发时间
        String departureTime = StrKit.str(jsonObject.get("departureTime"));
        //订单状态
        String msgInfo = StrKit.str(jsonObject.get("msgInfo"));
        //到达时间
        String arrivalTime = StrKit.str(jsonObject.get("arrivalTime"));
        //原订单号
        String originalOrderNo = StrKit.str(jsonObject.get("originalOrderNo"));
        //组负责人
        String outEmployeeIdZ = StrKit.str(jsonObject.get("outEmployeeId"));
        //获取差旅信息
        Map<String,Object> travelData = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("travelData")),Map.class);
        //oa申请单号
        String travelApplyNo = StrKit.str(travelData.get("TravelApplyNo"));

        List<Map<String,Object>> hcOrderDetails = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("passengers")), List.class);
        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        //循环添加
        for (Map<String, Object> passenger : hcOrderDetails) {
            //外部员工id
            String outEmployeeId = StrKit.str(passenger.get("outEmployeeId"));
            //价格
            String price = StrKit.str(passenger.get("price"));
            V3xOrgMember member = null;
            try {
                member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
            } catch (BusinessException e) {
                log.info("火车订单-根据外部人员获取人员Id 异常！", e);
            }

            //获取需要回写的字段信息
            HashMap<String, Object> hcMap = new HashMap<>();
            hcMap.put("出差人工号",member != null?member.getCode():"");
            hcMap.put("出差人",member != null?member.getId():"");
            hcMap.put("出差申请单号",travelApplyNo);
            hcMap.put("订单类型","火车订单");
            hcMap.put("订单状态",msgInfo);
            hcMap.put("价格",price);

            hcMap.put("出发入住日期",departureTime);
            hcMap.put("到达离开日期",arrivalTime);
            hcMap.put("出发地",fromStation);
            hcMap.put("目的地",toStation);
            hcMap.put("同程单号",orderNo);
            hcMap.put("上车地点",fromStation);
            hcMap.put("下车地点",toStation);
            hcMap.put("原订单号",originalOrderNo);

            //组装主表和明细表数据map
            HashMap<String,Object> mapData = new HashMap<>();
            mapData.put("masterData",hcMap);
            mapData.put("mxData",null);
            maps.add(mapData);
        }
        try {
            if(!outEmployeeIdZ.equals("")){
                V3xOrgMember orgMember = orgManager.getMemberById(Long.valueOf(outEmployeeIdZ));
                if(orgMember == null){
                    log.info("获取人员【"+outEmployeeIdZ+"】异常！");
                    return new ResountEntity(true,"1","回写火车订单失败");
                }
                FormCap4Kit.saveCAP4FormData(orgMember,HC_NUMBER,maps,false);
            }else{
                log.info("获取组负责人【"+outEmployeeIdZ+"】为空！");
            }
        } catch (Exception e) {
            log.info("添加火车-占座数据失败：",e);
        }
        return new ResountEntity(true,"100","回写火车订单成功");
    }



    //出票
    private ResountEntity drawABill(String notifyData){
        JSONObject jsonObject = JSON.parseObject(notifyData);
        //订单编号
        String orderNo = StrKit.str(jsonObject.get("orderNo"));
        //消息内容
        String msgInfo = StrKit.str(jsonObject.get("msgInfo"));
        Map<String,Object> travelDataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("travelData")),Map.class);
        //获取出差申请单号
        String travelApplyNo = StrKit.str(travelDataMap.get("TravelApplyNo"));
        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        //外部员工id
        String outEmployeeId = StrKit.str(jsonObject.get("outEmployeeId"));
        //价格
        String price = StrKit.str(jsonObject.get("CompanyPrice"));
        //出发城市
        String departCityName = StrKit.str(jsonObject.get("departCityName"));
        //到达城市
        String arriveCityName = StrKit.str(jsonObject.get("arriveCityName"));
        //原订单号
        String originalOrderNo = StrKit.str(jsonObject.get("originalOrderNo"));
        V3xOrgMember member = null;
        try {
            member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
        } catch (BusinessException e) {
            log.info("火车订单-根据外部人员获取人员Id 异常！", e);
        }

        //获取需要回写的字段信息
        HashMap<String, Object> hcMap = new HashMap<>();
        hcMap.put("出差人工号",member != null?member.getCode():"");
        hcMap.put("出差人",member != null?member.getId():"");
        hcMap.put("出差申请单号",travelApplyNo);
        hcMap.put("订单类型","火车订单");
        hcMap.put("订单状态",msgInfo);
        hcMap.put("价格",price);

        hcMap.put("出发入住日期","");
        hcMap.put("到达离开日期","");
        hcMap.put("出发地",departCityName);
        hcMap.put("目的地",arriveCityName);
        hcMap.put("同程单号",orderNo);
        hcMap.put("上车地点","");
        hcMap.put("下车地点","");
        hcMap.put("原订单号",originalOrderNo);

        //组装主表和明细表数据map
        HashMap<String,Object> mapData = new HashMap<>();
        mapData.put("masterData",hcMap);
        mapData.put("mxData",null);
        maps.add(mapData);
        try {
            FormCap4Kit.saveCAP4FormData(member,HC_NUMBER,maps,false);
        } catch (Exception e) {
            log.info("添加火车票-出票数据失败：",e);
        }
        return new ResountEntity(true,"100","回写火车订单成功");
    }



    //退票
    private ResountEntity refundTicket(String notifyData){
        JSONObject jsonObject = JSON.parseObject(notifyData);
        //订单编号
        String orderNo = StrKit.str(jsonObject.get("orderNo"));
        //退票类型
        String refundType = StrKit.str(jsonObject.get("refundType"));
        //消息内容
        String msgInfo = StrKit.str(jsonObject.get("msgInfo"));
        //原订单号
        String originalOrderNo = StrKit.str(jsonObject.get("originalOrderNo"));
        //组负责人
        String outEmployeeIdZ = StrKit.str(jsonObject.get("outEmployeeId"));
        //出发城市
        String departCityName = StrKit.str(jsonObject.get("departCityName"));
        //到达城市
        String arriveCityName = StrKit.str(jsonObject.get("arriveCityName"));
        if(refundType.equals("online")){
            msgInfo = "线上"+msgInfo;
        }else{
            msgInfo = "车站"+msgInfo;
        }

        Map<String,Object> travelDataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("travelData")),Map.class);
        //获取人员信息
        List<Map<String,Object>> hcOrderDetails = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("passengers")), List.class);
        //获取出差申请单号
        String travelApplyNo = StrKit.str(travelDataMap.get("TravelApplyNo"));

        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        //循环添加
        for (Map<String, Object> passenger : hcOrderDetails) {
            //外部员工id
            String outEmployeeId = StrKit.str(passenger.get("outEmployeeId"));
            //价格
            String price = StrKit.str(passenger.get("refundPrice"));
            if(!price.contains("-")){
                price = "-"+price;
            }
            //服务费
            String servicePrice = StrKit.str(passenger.get("servicePrice"));
            //退票费
            String RefundFee = StrKit.str(passenger.get("RefundFee"));
            price = String.valueOf(Double.parseDouble(price)+Double.parseDouble(servicePrice)+Double.parseDouble(RefundFee));
            V3xOrgMember member = null;
            try {
                member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
            } catch (BusinessException e) {
                log.info("火车订单-根据外部人员获取人员Id 异常！", e);
            }

            //获取需要回写的字段信息
            HashMap<String, Object> hcMap = new HashMap<>();
            hcMap.put("出差人工号",member != null?member.getCode():"");
            hcMap.put("出差人",member != null?member.getId():"");
            hcMap.put("出差申请单号",travelApplyNo);
            hcMap.put("订单类型","火车订单");
            hcMap.put("订单状态",msgInfo);
            hcMap.put("价格",price);

            hcMap.put("出发入住日期","");
            hcMap.put("到达离开日期","");
            hcMap.put("出发地",departCityName);
            hcMap.put("目的地",arriveCityName);
            hcMap.put("同程单号",orderNo);
            hcMap.put("上车地点","");
            hcMap.put("下车地点","");
            hcMap.put("原订单号",originalOrderNo);

            //组装主表和明细表数据map
            HashMap<String,Object> mapData = new HashMap<>();
            mapData.put("masterData",hcMap);
            mapData.put("mxData",null);
            maps.add(mapData);
        }
        try {
            if(!outEmployeeIdZ.equals("")){
                V3xOrgMember orgMember = orgManager.getMemberById(Long.valueOf(outEmployeeIdZ));
                if(orgMember == null){
                    log.info("获取人员【"+outEmployeeIdZ+"】异常！");
                    return new ResountEntity(true,"1","回写火车订单失败");
                }
                FormCap4Kit.saveCAP4FormData(orgMember,HC_NUMBER,maps,false);
            }else{
                log.info("获取组负责人【"+outEmployeeIdZ+"】为空！");
            }
        } catch (Exception e) {
            log.info("添加火车票-退票数据失败：",e);
        }
        return new ResountEntity(true,"100","回写火车订单成功");
    }


    //取消订单
    private ResountEntity cancelOrder(String notifyData){
        JSONObject jsonObject = JSON.parseObject(notifyData);
        //订单编号
        String orderNo = StrKit.str(jsonObject.get("orderNo"));
        //消息内容
        String msgInfo = StrKit.str(jsonObject.get("msgInfo"));
        Map<String,Object> travelDataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("travelData")),Map.class);
        //获取出差申请单号
        String travelApplyNo = StrKit.str(travelDataMap.get("TravelApplyNo"));
        //保存表单数据集合
        List<HashMap<String,Object>> maps = new ArrayList<>();
        //外部员工id
        String outEmployeeId = StrKit.str(jsonObject.get("outEmployeeId"));
        //价格
        String price = StrKit.str(jsonObject.get("CompanyPrice"));
        //出发城市
        String departCityName = StrKit.str(jsonObject.get("departCityName"));
        //到达城市
        String arriveCityName = StrKit.str(jsonObject.get("arriveCityName"));
        //原订单号
        String originalOrderNo = StrKit.str(jsonObject.get("originalOrderNo"));
        V3xOrgMember member = null;
        try {
            member = orgManager.getMemberById(Long.valueOf(outEmployeeId));
        } catch (BusinessException e) {
            log.info("火车订单-根据外部人员获取人员Id 异常！", e);
        }

        //获取需要回写的字段信息
        HashMap<String, Object> hcMap = new HashMap<>();
        hcMap.put("出差人工号",member != null?member.getCode():"");
        hcMap.put("出差人",member != null?member.getId():"");
        hcMap.put("出差申请单号",travelApplyNo);
        hcMap.put("订单类型","火车订单");
        hcMap.put("订单状态",msgInfo);
        hcMap.put("价格",price);

        hcMap.put("出发入住日期","");
        hcMap.put("到达离开日期","");
        hcMap.put("出发地",departCityName);
        hcMap.put("目的地",arriveCityName);
        hcMap.put("同程单号",orderNo);
        hcMap.put("上车地点","");
        hcMap.put("下车地点","");
        hcMap.put("原订单号",originalOrderNo);

        //组装主表和明细表数据map
        HashMap<String,Object> mapData = new HashMap<>();
        mapData.put("masterData",hcMap);
        mapData.put("mxData",null);
        maps.add(mapData);
        try {
            FormCap4Kit.saveCAP4FormData(member,HC_NUMBER,maps,false);
        } catch (Exception e) {
            log.info("添加火车票-取消数据失败：",e);
        }
        return new ResountEntity(true,"100","回写火车订单成功");
    }






    /**
     * 切换订单子类型
     * 1-占座 2-出票 3-退票 4-邮寄 5-占座出票合并 6-订单过期 7-支付 8-购保 9-退保 10-抢票出票 11-抢票过期 12-抢票占座 13-取消订单 14-停运 15-H5出票推送
     * @return
     */
    private String getSubNotifyType(String subNotifyType){
        if(subNotifyType.equals("1")){
            subNotifyType = "占座";
        }else if(subNotifyType.equals("2")){
            subNotifyType = "出票";
        }else if(subNotifyType.equals("3")){
            subNotifyType = "退票";
        }else if(subNotifyType.equals("4")){
            subNotifyType = "邮寄";
        }else if(subNotifyType.equals("5")){
            subNotifyType = "占座出票合并";
        }else if(subNotifyType.equals("6")){
            subNotifyType = "订单过期";
        }else if(subNotifyType.equals("7")){
            subNotifyType = "支付";
        }else if(subNotifyType.equals("8")){
            subNotifyType = "购保";
        }else if(subNotifyType.equals("9")){
            subNotifyType = "退保";
        }else if(subNotifyType.equals("10")){
            subNotifyType = "抢票出票";
        }else if(subNotifyType.equals("11")){
            subNotifyType = "抢票过期";
        }else if(subNotifyType.equals("12")){
            subNotifyType = "抢票占座";
        }else if(subNotifyType.equals("13")){
            subNotifyType = "取消订单";
        }else if(subNotifyType.equals("14")){
            subNotifyType = "停运";
        }else if(subNotifyType.equals("15")){
            subNotifyType = "H5出票推送";
        }else if(subNotifyType.equals("17")){
            subNotifyType = "调价单";
        }
        return subNotifyType;
    }


    /**
     * 给主表
     * @param masterId
     * @param formBean
     * @param filedName
     * @param fieldValue
     * @throws BusinessException
     * @throws SQLException
     */
    private void updateWuxiao(Long masterId,FormBean formBean,String filedName,String fieldValue) throws BusinessException, SQLException {
        FormDataMasterBean dataMasterBean = cap4FormManager.findDataById(masterId, formBean, null);
        dataMasterBean.addFieldValue(filedName,fieldValue);
        cap4FormDataManager.insertOrUpdateMasterData(dataMasterBean);
    }


}
